from django.shortcuts import render

# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
# from rest_framework.decorators import api_view
from .models import Person  # 导入你的模型


class PersonGetUserIDAPIView(APIView):
    def get(self, request, *args, **kwargs):
        # 获取 URL 参数
        user_name = request.query_params.get('user_name', None)

        # 如果参数为空，返回错误信息
        if not user_name:
        # if not name or not last_name:
            return Response(
                {"error": "搜索名称不可为空！"},
                status=status.HTTP_400_BAD_REQUEST
            )

        # 查询数据库，查找符合条件的记录
        try:
            results = Person.objects.filter(user_name=user_name)
            
            # 如果没有找到记录，返回 404
            if not results.exists():
                return Response(
                    {"error": "没有该名称的人！"},
                    status=status.HTTP_404_NOT_FOUND
                )

            # 将查询结果转换为字典格式
            # data = {
            #     "data": [
            #         {
            #             "name": result.user_name,
            #             "email": result.email,
            #             "age": result.age,
            #             "created_at": result.created_at
            #         }
            #         for result in results
            #     ]
            # }

            data = [
                {
                    "name": result.user_name,
                    "email": result.email,
                    "age": result.age,
                    "created_at": result.created_at
                }
                for result in results
            ]
            # 如果结果为空，返回一个提示信息
            # if not data:
            #     return Response({"message": "没有找到相关数据！"}, status=status.HTTP_404_NOT_FOUND)

            return Response({"message": "查询成功！","data":data},status=status.HTTP_200_OK)
        
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)

class PersonCreateAPIView(APIView):
     # 新增员工
    def post(self, request, *args, **kwargs):
        # 获取 form-data 中的字段
        user_name = request.POST.get('user_name', None)
        email = request.POST.get('email', None)
        age = request.POST.get('age', None)

         # 如果参数为空，返回错误信息
        if not user_name or not email or not age:
        # if not name or not last_name:
            return Response(
                {"error": "必填参数不可为空！"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 查询数据库，查找符合条件的记录
        try:
             # 创建并保存新员工
            new_Person = Person.objects.create(
                user_name=user_name,
                email=email,
                age=age
            )
            
            return Response({"message": "新建员工成功！", "book": {"user_name": new_Person.user_name, "email": new_Person.email, "age": new_Person.age}},status=status.HTTP_200_OK)
        
        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        

class PersonUpdateUserView(APIView):
     # 修改员工
    def put(self, request, *args, **kwargs):
        # 获取 form-data 中的字段
        user_id = request.POST.get('user_id', None)
        user_name = request.POST.get('user_name', None)
        email = request.POST.get('email', None)
        age = request.POST.get('age', None)

         # 如果参数为空，返回错误信息
        if not user_id:
        # if not name or not last_name:
            return Response(
                {"error": "必填参数不可为空！"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        # 查询数据库，查找符合条件的记录
        try:
            results = Person.objects.get(id=user_id)

            # 检查邮箱是否已存在
            if Person.objects.filter(email=email).exclude(id=user_id).exists():
                return Response({"message": "该邮箱已被使用，请使用其他邮箱！"}, status=status.HTTP_400_BAD_REQUEST)

            # 编辑并保存员工   update 方法并不是用来创建或编辑单个对象的，而是用来批量更新符合条件的多个对象的。因此，在你的代码中，update 用法并不适用
            # edit_Person = Person.objects.update(
            #     id=user_id,
            #     user_name=user_name,
            #     email=email,
            #     age=age,
            # )

            results.user_name = user_name
            results.email = email
            results.age = age
            # results.update(is_active=False)  # 使用 update 批量更新字段
            results.save()    # 保存修改后的对象
            
            return Response({"message": "编辑员工成功！", "book": {"user_name": results.user_name, "email": results.email, "age": results.age}},status=status.HTTP_200_OK)
        
        except Person.DoesNotExist:
            # 如果没有找到该员工，返回 404 错误
            return Response({"error": "没有找到该员工！"}, status=status.HTTP_404_NOT_FOUND)

        except Exception as e:
            return Response(
                {"error": str(e)},
                status=status.HTTP_500_INTERNAL_SERVER_ERROR)
        

# @api_view(['DELETE'])        
class PersonDelUserView(APIView):
    def delete(self, request, *args, **kwargs):

        # 获取 form-data 中的字段
        user_id = request.POST.get('user_id', None)

         # 如果参数为空，返回错误信息
        if not user_id:
        # if not name or not last_name:
            return Response(
                {"error": "必填参数不可为空！"},
                status=status.HTTP_400_BAD_REQUEST
            )
        
        try:
            # 获取指定 id 的人员记录
            person = Person.objects.get(id=user_id)

            # 删除该记录
            person.delete()

            # 返回成功响应
            return Response(
                {"message": "删除员工成功！"},
                status=status.HTTP_200_OK
            )

        except Person.DoesNotExist:
            # 如果没有找到该员工，返回 404 错误
            return Response({"error": "没有找到该员工！"}, status=status.HTTP_404_NOT_FOUND)

        except Exception as e:
            # 捕获其他异常并返回 500 错误
            return Response({"error": str(e)}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
